package com.linking.web.manager;

import com.linking.controller.common.LocaleHolder;
import com.linking.web.common.BaseResult;
import com.linking.web.common.BaseResult.CodeEnum;
import javax.annotation.Resource;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

/**
 * @Author YaoWeiXin
 * @Date 2020/4/22 11:29
 * @Description 返回结果管理器
 */
@Component
public class ResultManager {

  @Resource
  private MessageSource messageSource;

  private <T> BaseResult<T> gen() {
    return gen(null);
  }

  private <T> BaseResult<T> gen(T t) {
    BaseResult<T> result = new BaseResult<>();
    if (t != null) {
      result.setData(t);
    }
    return result;
  }

  public <T> BaseResult<T> genOk() {
    return gen();
  }

  public <T> BaseResult<T> genOk(T t) {
    return gen(t);
  }

  public BaseResult ofSysError() {
    return ofFail(CodeEnum.Busy);
  }

  public BaseResult ofFail(CodeEnum codeEnum) {
    return ofFail(codeEnum.getCode());
  }

  public BaseResult ofFail(String code) {
    return ofFail(code, getMessage(code));
  }

  public BaseResult ofFail(String code, String desc) {
    BaseResult result = new BaseResult();
    result.setSuccess(false);
    result.setCode(code);
    result.setDesc(desc);
    return result;
  }

  /**
   * 根据指定的KEY活参数获取多语言字符串，通过LocaleHolder获得语言
   *
   * @param msgKey 消息KEY
   * @param params 消息替换参数
   * @return 多语言字符串
   */
  public String getMessage(String msgKey, Object... params) {
    Object[] objs;
    if (params != null) {
      objs = new Object[params.length];
      System.arraycopy(params, 0, objs, 0, params.length);
    } else {
      objs = new Object[0];
    }
    return messageSource.getMessage(msgKey, objs, LocaleHolder.get());
  }
}
